﻿Imports Microsoft.TeamFoundation.VersionControl.Client
Imports System.Collections.Generic
Imports TfsSearchCode


Public Class frmMain

    Dim RootNode As String = "$/"
    Dim MyTfsSearchCode As New TfsSearchCode.TFSSearchCodeClass


    Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click

        If btnConnect.Text = "&Connect to TFS" Then
            btnConnect.Text = "&Disconnect from TFS"

            Try
                MyTfsSearchCode.Connect(txtLogin.Text, txtPass.Text, txtIP.Text)

            Catch ex As Exception

                MsgBox(ex.Message.ToString)
                Exit Sub

            End Try


            'Adapt user interface to logon ok
            ToolStripStatusLabel1.Text = "Connected sucessfully!!!! Loading folders ...."
            ToolStripStatusLabel1.Visible = True

            GroupBox1.Enabled = True

            PictureBox1.Visible = True

            'load folders on backgrounder
            BackgroundWorker2.RunWorkerAsync(MyTfsSearchCode)

        Else

            btnConnect.Text = "&Connect to TFS"
            TreeView1.Nodes.Clear()
            ListView1.Items.Clear()
            RootNode = "$/"

        End If


    End Sub

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        'exiting, save datas always are sames
        SaveSetting(My.Application.Info.AssemblyName, "CONF", "IP", txtIP.Text)
        SaveSetting(My.Application.Info.AssemblyName, "CONF", "LOGIN", txtLogin.Text)
        SaveSetting(My.Application.Info.AssemblyName, "CONF", "PASS", txtPass.Text)

    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        'loading, load habitual data
        txtIP.Text = GetSetting(My.Application.Info.AssemblyName, "CONF", "IP", "http://0.0.0.0:8080")
        txtLogin.Text = GetSetting(My.Application.Info.AssemblyName, "CONF", "LOGIN", "")
        txtPass.Text = GetSetting(My.Application.Info.AssemblyName, "CONF", "PASS", "")

        AddHandler MyTfsSearchCode.ProgressSearchingFolders, AddressOf ProgressChangedFoldersSearch
        AddHandler MyTfsSearchCode.ProgressSearchingText, AddressOf ProgressChangedTextSearch


    End Sub

    Private Sub bntSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bntSearch.Click

        ListView1.Items.Clear()

        'Warning, a sdeacrh with blanks produces intinity results!!!!
        If String.IsNullOrEmpty(txtText.Text) Then
            MsgBox("You must specify a text to search")
            Exit Sub
        End If

        'adap User Interface to started process
        Me.ToolStripProgressBar1.Visible = True
        Me.ToolStripProgressBar1.ProgressBar.Value = 1
        Me.PictureBox1.Visible = True

        'start searching in background processing
        MyTfsSearchCode.SensitiveSearch = chkSensitive.Checked
        BackgroundWorker1.RunWorkerAsync(MyTfsSearchCode)

    End Sub

    Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

        Dim oTfsSearchCode As TFSSearchCodeClass = CType(e.Argument, TFSSearchCodeClass)

        BackgroundWorker1.WorkerReportsProgress = True

        Try

            oTfsSearchCode.SearchTextInCode(RootNode, txtPattern.Text, txtText.Text)

        Catch ex As Exception

            e.Cancel = True
            e.Result = ex.Message.ToString
            Exit Sub

        End Try

        e.Result = oTfsSearchCode


    End Sub

    Public Sub ProgressChangedTextSearch(ByVal Progress As Integer)

        BackgroundWorker1.ReportProgress(Progress)

    End Sub

    Public Sub ProgressChangedFoldersSearch(ByVal Progress As Integer)

        BackgroundWorker2.ReportProgress(Progress)

    End Sub

    Private Sub ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged, BackgroundWorker2.ProgressChanged
        Me.ToolStripProgressBar1.ProgressBar.Increment(e.ProgressPercentage)
    End Sub


    Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted

        Me.PictureBox1.Visible = False
        Me.ToolStripProgressBar1.Visible = False

        If e.Cancelled = True Then
            Me.ToolStripStatusLabel1.Text = "Canceled: " & IIf(e.Result IsNot Nothing, e.Result.ToString, "(without information)")
        Else

            If e.Result IsNot Nothing Then

                Dim colItems As List(Of ItemSource) = CType(e.Result, TFSSearchCodeClass).ItemsSource

                For Each sourceItem As ItemSource In colItems

                    Dim lvi As ListViewItem
                    lvi = New ListViewItem(sourceItem.Path)
                    lvi.SubItems.Add(sourceItem.File)
                    lvi.SubItems.Add(sourceItem.LineNumber.ToString)
                    lvi.SubItems.Add(sourceItem.LineCode)
                    lvi.Tag = sourceItem.MiExtendedItem
                    ListView1.Items.Add(lvi)

                Next

                ToolStripStatusLabel1.Text = "Time to process in seconds: " & (CType(e.Result, TFSSearchCodeClass).TimeEmployedAction).ToString

            End If

        End If

    End Sub

    Private Sub ListView1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ListView1.KeyPress
        If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Return) Then
            LaunchViewer()
        End If
    End Sub

    Private Sub ListView1_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseDoubleClick

        LaunchViewer()

    End Sub

    Private Sub LaunchViewer()

        If ListView1.SelectedItems IsNot Nothing Then

            If ListView1.SelectedItems.Count > 0 Then

                Dim miItem As ExtendedItem = CType(ListView1.SelectedItems(0).Tag, ExtendedItem)
                Dim fileTmp As String = System.IO.Path.Combine(System.IO.Path.GetTempPath(), ListView1.SelectedItems(0).SubItems(1).Text)

                MyTfsSearchCode.GetLatestVersion(miItem.SourceServerItem, fileTmp)


                Dim frm As frmSourceViewer
                frm = New frmSourceViewer
                frm.FileToShow = fileTmp
                frm.TextSearch = txtText.Text
                frm.SensitiveSearch = chkSensitive.Checked
                frm.LineFound = Val(ListView1.SelectedItems(0).SubItems(2).Text)
                frm.ShowDialog()


            End If


        End If

    End Sub

    Private Sub BackgroundWorker2_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker2.DoWork

        Dim oTfsSearchCode As TFSSearchCodeClass = CType(e.Argument, TFSSearchCodeClass)

        BackgroundWorker2.WorkerReportsProgress = True

        Try

            oTfsSearchCode.LoadFoldersOnTFsServer(RootNode)

        Catch ex As Exception

            e.Cancel = True
            e.Result = ex.Message.ToString
            Exit Sub

        End Try

        e.Result = oTfsSearchCode

    End Sub

    Private Sub BackgroundWorker2_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker2.ProgressChanged
        Me.ToolStripProgressBar1.ProgressBar.Increment(e.ProgressPercentage)
    End Sub

    Private Sub BackgroundWorker2_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker2.RunWorkerCompleted


        If e.Cancelled = True Then

            Me.ToolStripStatusLabel1.Text = "Canceled: " & IIf(e.Result IsNot Nothing, e.Result.ToString, "(without information)")

        Else

            If e.Result IsNot Nothing Then

                Dim Items() As String = CType(e.Result, TFSSearchCodeClass).Folders

                'neccessary to sort
                Dim colItems As New List(Of String)
                colItems.InsertRange(0, Items)
                colItems.Sort()


                Dim Primero As TreeNode = New TreeNode("$/")
                If Primero IsNot Nothing Then

                    TreeView1.Nodes.Add(Primero)

                End If
                Dim i As Long = 0




                For Each sourceItem As String In colItems

                    sourceItem = sourceItem.Replace("$/", "")

                    If sourceItem.Trim() > "" Then

                        i += 1

                        Try
                            Dim levels() As String = Split(sourceItem, "/")

                            Dim NameLevel As String = levels(UBound(levels))
                            levels(UBound(levels)) = ""

                            Dim ParentLevel As String = Join(levels, "/")
                            If Len(ParentLevel) > 1 Then
                                ParentLevel = Mid(ParentLevel, 1, Len(ParentLevel) - 1)
                            End If

                            Dim Parent As TreeNode = Nothing

                            If ParentLevel.Trim = "" Then
                                Parent = Primero
                            Else
                                Try
                                    Parent = TreeView1.Nodes.Find(ParentLevel, True)(0)
                                Catch ex As Exception
                                    Parent = Primero
                                End Try
                            End If

                            Parent.Nodes.Add(sourceItem, NameLevel)

                        Catch ex As Exception

                            MsgBox("compose tree nodes on source control" & vbCrLf & ex.Message.ToString)
                            Debug.Print("")

                        End Try

                    End If

                Next

                Primero.Expand()

                ToolStripStatusLabel1.Text = "Time to process in seconds: " & (CType(e.Result, TFSSearchCodeClass).TimeEmployedAction).ToString
                ToolStripStatusLabel1.Visible = True

            End If

        End If


        Me.PictureBox1.Visible = False
        Me.ToolStripProgressBar1.Visible = False

    End Sub

    Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
        If TreeView1.SelectedNode IsNot Nothing Then
            RootNode = "$/" & TreeView1.SelectedNode.Name
            lbStart.Text = "Start search on: " & RootNode
        End If
    End Sub

    Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Shell(Chr(34) & "%HOMEDRIVE%%HOMEPATH%\iexplorer.exe" & Chr(34) & " http://copermatica.es")


    End Sub

    Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        If My.Computer.Network.IsAvailable Then

            Shell(My.Computer.FileSystem.SpecialDirectories.ProgramFiles & _
                    "\Internet Explorer\iexplore.exe HTTP://copermatica.es", AppWinStyle.NormalFocus, False)

        Else

            MsgBox("http://Copermatica.es")

        End If
    End Sub

    Private Sub LinkLabel2_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel2.LinkClicked
        If My.Computer.Network.IsAvailable Then

            Shell(My.Computer.FileSystem.SpecialDirectories.ProgramFiles & _
                    "\Internet Explorer\iexplore.exe HTTP://tfssearchcode.codeplex.com", AppWinStyle.NormalFocus, False)

        Else

            MsgBox("http://tfssearchcode.codeplex.com")

        End If
    End Sub
End Class
